package com.bimrun.gis.util;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.Map;

@Component
public class CesiumAssetTokenManage {

    private Gson json = new Gson();
    private final Object lock = new Object();

    @Value("${bimrun.cesiumAssetToken}")
    private String accessToken;

    @Autowired
    private HttpClientUtil httpClientUtil;

    private AssertsToken terrainAccessToken = new AssertsToken(1);
    private AssertsToken imageAccessToken = new AssertsToken(3954);

    public String getTerrainToken() throws IOException, URISyntaxException {
        return terrainAccessToken.getAssetsToken();
    }

    public String getImageToken() throws IOException, URISyntaxException {
        return imageAccessToken.getAssetsToken();
    }

    private class AssertsToken {
        private String assetsToken;
        private long lastRefreshTime = 0;
        private int assetId;
        private URI requestUrl;

        public AssertsToken(int assetId) {
            this.assetId = assetId;
        }

        public String getAssetsToken() throws IOException, URISyntaxException {
            refreshToken();
            return assetsToken;
        }

        public void refreshToken() throws IOException, URISyntaxException {
            //五分钟超时，todo 改成定时刷新能提高一定的可用性，稳定性
            if (new Date().getTime() - lastRefreshTime < 300000) return;
            synchronized (lock) {
                if (new Date().getTime() - lastRefreshTime < 300000) return;
                HttpClientUtil.RequestBuilder requestBuilder = httpClientUtil.buildRequest().buildGet(getRequestRrl());
                String string = requestBuilder.getResponse().getString();
                Map<String, String> stringObjectMap = json.fromJson(string, Map.class);
                assetsToken = (String) stringObjectMap.get("accessToken");
                lastRefreshTime = new Date().getTime();
            }
        }

        private URI getRequestRrl() throws URISyntaxException {
            if (requestUrl == null)
                requestUrl = new URI("https://api.cesium.com/v1/assets/" + assetId + "/endpoint?access_token=" + accessToken);
            return requestUrl;
        }

    }
}
